package com.dsk.connector.commons.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;

import java.util.Enumeration;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ConfigUtils {
    private static Environment environment;

    public static Environment getEnvironment() {
        return environment;
    }

    public static void setEnvironment(Environment environment) {
        ConfigUtils.environment = environment;
    }

    public static String getConfigItem(String item){
        return environment.getProperty(item);
    }

    /**
     * 替换property属性值中的占位符
     * @param props
     * @return
     */
    public static Properties replacePlaceholders(Properties props){
        Enumeration nameEnum=props.propertyNames();
        Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}");
        while(nameEnum.hasMoreElements()){
            String name=(String)nameEnum.nextElement();
            String value=props.getProperty(name);
            Matcher matcher=pattern.matcher(value);
            String newValue=value;
            while (matcher.find()){
                String placeHolder=matcher.group(0);
                String holder=matcher.group(1);
                if(StringUtils.isBlank(holder)){
                    continue;
                }
                if(environment.containsProperty(holder)){
                    String holderValue=environment.getProperty(holder);
                    newValue=newValue.replace(placeHolder,holderValue);
                }
            }
            props.setProperty(name,newValue);
        }
        return props;
    }
}
